import config from "@/config/index.js"

// 请求拦截器数组（可 push 自定义拦截器）
const reqInterceptors = []
const resInterceptors = []

/* 核心请求方法 --------------------------------------------------*/
function request(options) {
	// 1. 合并默认参数
	const {
		url,
		method = 'GET',
		data = {},
		header = {},
		showLoading = true, // 是否显示 loading
		loadingTitle = '加载中...',
		needToken = true // 是否自动带 token（可按需改）
	} = options

	// 2. 请求拦截
	let sendConfig = {
		url,
		method,
		data,
		header,
		showLoading,
		loadingTitle,
		needToken
	}
	for (const fn of reqInterceptors) {
		sendConfig = fn(sendConfig) || sendConfig
	}

	// 3. loading
	if (showLoading) {
		uni.showLoading({
			title: loadingTitle,
			mask: true
		})
	}

	// 4. 发起请求
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.BASE_URL + sendConfig.url,
			method: sendConfig.method,
			data: sendConfig.data,
			header: sendConfig.header,
			timeout: config.TIME_OUT,
			success: (res) => {
				// 5. 响应拦截
				let result = res
				for (const fn of resInterceptors) {
					result = fn(result) || result
				}
				if(result.data.code != 200){
					uni.showToast({
						duration: 2000,
						title: result.data.message || "系统异常",
						icon: "none"
					})
					reject(result)
					return
				}
				console.log(result.data)
				resolve(result.data)
			},
			fail: (err) => {
				// 6. 异常提示
				uni.showToast({
					duration: 2000,
					title: err.errMsg || '网络异常',
					icon: 'none'
				})
				reject(err)
			},
			complete: () => {
				if (showLoading) uni.hideLoading()
			}
		})
	})
}

/* 快捷方法 ------------------------------------------------------*/
const http = {
	get: (url, data, opts) => request({
		url,
		method: 'GET',
		data,
		...opts
	}),
	post: (url, data, opts) => request({
		url,
		method: 'POST',
		data,
		...opts
	}),
	upload: (url, filePath, formData = {}, opts) => {
		return new Promise((resolve, reject) => {
			if (opts?.showLoading) uni.showLoading({
				title: '上传中...',
				mask: true
			})
			uni.uploadFile({
				url: config.BASE_URL + url,
				filePath,
				name: opts.name || 'file',
				formData,
				success: (res) => resolve(JSON.parse(res.data)),
				fail: (err) => {
					uni.showToast({duration: 2000,
						title: '上传失败',
						icon: 'none'
					});
					reject(err)
				},
				complete: () => {
					if (opts?.showLoading) uni.hideLoading()
				}
			})
		})
	},
	download: (url, opts) => {
		return new Promise((resolve, reject) => {
			if (opts?.showLoading) uni.showLoading({
				title: '下载中...',
				mask: true
			})
			uni.downloadFile({
				url: config.BASE_URL + url,
				success: (res) => resolve(res.tempFilePath),
				fail: (err) => {
					uni.showToast({duration: 2000,
						title: '下载失败',
						icon: 'none'
					});
					reject(err)
				},
				complete: () => {
					if (opts?.showLoading) uni.hideLoading()
				}
			})
		})
	}
}

/* 拦截器注册 API ------------------------------------------------*/
http.addReqInterceptor = (fn) => reqInterceptors.push(fn)
http.addResInterceptor = (fn) => resInterceptors.push(fn)

export default http